﻿using System;
using System.Collections.Generic;
using System.Linq;
namespace WCF.Common.DAL
{
    public class ParameterDAL : BaseDAL
    {
        public string Search(string key)
        {
            string result = string.Empty;
            var context = GetDataContext();
            if (context.Parameters.Any(p => p.Key == key))
            {
                result = context.Parameters.First(p => p.Key == key).Value;
            }
            return result;
        }

        public OperateResult Update(string key, string value)
        {
            try
            {
                var context = GetDataContext();
                if (context.Parameters.Any(p => p.Key == key))
                {
                    var item = context.Parameters.First(p => p.Key == key);
                    if (string.IsNullOrEmpty(value))
                    {
                        context.Parameters.DeleteOnSubmit(item);
                    }
                    else
                    {
                        item.Value = value;
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(value) == false)
                    {
                        context.Parameters.InsertOnSubmit(new Parameters() { Key = key, Value = value });
                    }
                }
                context.SubmitChanges();
            }
            catch (Exception ex)
            {
                return new OperateResult() { IsSuccess = false,Message= ex.Message };
            }
            return new OperateResult() { IsSuccess = true };
        }
    }
}